//
//  NoteView.m
//  PlayView
//
//  Created by houshijia on 16/9/25.
//  Copyright © 2016年 houshijia. All rights reserved.
//

#import "NoteView.h"
#import "ClassStateModel.h"
#import "NoteModel.h"
#import "NoteCell.h"
#import "WriteNoteViewController.h"
#import "CircleIcon.h"
#import "SCHeader.h"

@interface NoteView(){

    UILabel *_numLabel;//字数限制
    CircleIcon *_circleView;
}

@end

@implementation NoteView


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = Color_background;
        self.dataArr = [NSMutableArray array];
        self.request = nil;
        self.mlid = nil;
        self.tempMlid = nil;
        [self setupUI];
        [self writeNote];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        
    }
    return self;
}

#pragma mark- 设置model
-(void)setClassStateModel:(ClassStateModel *)classStateModel{
    super.classStateModel = classStateModel;
    if (super.classStateModel.kcid!=nil) {
        
        switch (super.classStateModel.ClassState) {
            case ClassStateUnopen:
                //空白页
                [self unOpen];
                break;
            case ClassStateKcls:
                [self normal];
                break;
            case ClassStateEncrypt:
                [self encrpyt];
                break;
            case ClassStateUnSelected:
                [self unSelect];
                break;
            case ClassStateisAuth:
                [self unSelect];
                break;
            case ClassStateisCharge:
                [self unSelect];
                break;
            case ClassStateSeleted:
                [self normal];
                break;
            case ClassStateNewJoin:
                [self newJoin];
                break;
            default:
                
                break;
        }
    }
}

#pragma mark- 设置mlid
-(void)setMlid:(NSString *)mlid{
    
    super.mlid = mlid;
    
    if (![self.mlid isEqualToString:_tempMlid]) {
        if (self.classStateModel.kcid!=nil) {
            _tempMlid = self.mlid;
            self.table.request_Model.kcid = self.classStateModel.kcid;
            self.table.request_Model.mlid = self.mlid;
            [self.table loadData];
           // self.mlid = nil;
        }
    }


}
-(void)writeNote{
    _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, SIZEHEIGHT )];
    _backView.backgroundColor = [UIColor blackColor];
    _backView.alpha = 0.65;
    
    
    _textView = [[UIView alloc]initWithFrame:CGRectMake(0, SIZEHEIGHT - 216 - 80-130, SIZEWIDTH, 130)];
    _textView.backgroundColor = [UIColor whiteColor];
    
    
    
    _accountTextFeild = [[JSTextView alloc]initWithFrame:CGRectMake(15, 15, SIZEWIDTH - 84, 50)];
    _accountTextFeild.delegate = self;
    _accountTextFeild.myPlaceholder = @"记录一下吧...";
    _accountTextFeild.backgroundColor = Color_background;
    _accountTextFeild.keyboardType = UIKeyboardTypeDefault;
    _accountTextFeild.keyboardAppearance = UIKeyboardAppearanceDefault;
    _accountTextFeild.returnKeyType = UIReturnKeyDefault;
    _accountTextFeild.layer.masksToBounds = YES;
    _accountTextFeild.layer.borderWidth = 0.5;
    _accountTextFeild.layer.borderColor = Color_line.CGColor;
    _accountTextFeild.layer.cornerRadius = 3;
    _accountTextFeild.font = NormalFont(28);
    [_textView addSubview:_accountTextFeild];

    
    _circleView = [[CircleIcon alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(_accountTextFeild.frame)+13, 18, 18)];
    [_textView addSubview:_circleView];
    
    _isOpen =YES;
    
    if (_isOpen == YES) {
        _circleView.colorState = ColorStateEmptyBlue;
    }else{
        _circleView.colorState = ColorStateEmptyGray;
    }
    UITapGestureRecognizer *tapCir = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openBtnClicked)];
    [_circleView addGestureRecognizer:tapCir];
    _circleView.userInteractionEnabled = YES;
    
    UILabel *openlable = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_circleView.frame)+10, CGRectGetMaxY(_accountTextFeild.frame)+13, 40, 18)];
    openlable.text = @"公开";
    openlable.textColor = Color_title_black_87;
    openlable.font = Fone_title30;
    [_textView addSubview:openlable];
    
    _numLabel = [[UILabel alloc]init];
    _numLabel.backgroundColor = Color_title_black_26;
    _numLabel.layer.masksToBounds = YES;
    _numLabel.layer.cornerRadius = 2;
    _numLabel.backgroundColor = Color_background;
    _numLabel.font = NormalFont(24);
    _numLabel.textAlignment = NSTextAlignmentCenter;
    _numLabel.textColor = Color_title_black_64;
    _numLabel.text = @"200";
    
    _numLabel.frame = CGRectMake(SIZEWIDTH-120, CGRectGetMaxY(_accountTextFeild.frame)+13, 50, 27);
    [_textView addSubview:_numLabel];
    
    UIButton *sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_accountTextFeild.frame),15, 70, 50)];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:Color_Main forState:UIControlStateNormal];
    sendBtn.titleLabel.font = NormalFont(28);
    [sendBtn addTarget:self action:@selector(sendBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [_textView addSubview:sendBtn];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGestureClicked:)];
    [_backView addGestureRecognizer:tap];
    
    
}

- (void)sendBtnClicked{

    NSString *str = [_accountTextFeild.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [_accountTextFeild resignFirstResponder];
    
    if (str.length==0 || [str isEqualToString:@""]) {
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"请输入笔记的内容 " imageView:FailImage inView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    else if (_accountTextFeild.text.length>200){
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"最多输入200字" imageView:FailImage inView:[UIApplication sharedApplication].keyWindow];
    }
    
    else{
        [self sendCourseNote];
    }

}

-(void)sendCourseNote{

    NSMutableDictionary *infoDic = [NSMutableDictionary dictionaryWithDictionary:self.classStateModel.currentInfo[@"info"]];

    if (_isOpen == YES) {
        [infoDic setObject:@1 forKey:@"sfgk"];
    }else{
        [infoDic setObject:@0 forKey:@"sfgk"];
    }
    [infoDic setObject:_accountTextFeild.text forKey:@"bjnr"];
    
    SCHttpRequest *request = [[SCHttpRequest alloc]initWithApi:API_wiritNote params:infoDic];
    
    [[SCUDUtil sharedInstance] doPOSTConnect:request start:^(SCHttpRequest * _Nonnull req) {
    
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        [self requestSendCrouseNoteFinished:resp.originalDictionary];
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {

    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];

}
#pragma mark - sendCrouseNote成功
-(void)requestSendCrouseNoteFinished:(NSDictionary*)operation{
    
    NSDictionary* cacheDic = [NSDictionary dictionaryWithDictionary:operation];
    NSLog(@"creartClasscacheDic == %@  %@", cacheDic,cacheDic[@"statusCode"]);
    
    if ([cacheDic[@"status"]integerValue] == 0) {
        _accountTextFeild.text = @"";
        _numLabel.text = @"200";
        [[JLActionManager sharedInstance]showHUDWithLabelText:@"发布成功" imageView:SucceedImage inView:[UIApplication sharedApplication].keyWindow];
        [self.table loadData];
        [_textView removeFromSuperview];
        [_backView removeFromSuperview];
        [_accountTextFeild resignFirstResponder];
    }else{
        [[JLActionManager sharedInstance]showHUDWithLabelText:cacheDic[@"statusCode"] imageView:FailImage inView:[UIApplication sharedApplication].keyWindow];
    }
}

#pragma mark 键盘将要出现
-(void)KeyboardWillShow:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    
    //获取高度
    NSValue *value = [info objectForKey:@"UIKeyboardBoundsUserInfoKey"];//关键的一句，网上关于获取键盘高度的解决办法，多到这句就over了。系统宏定义的UIKeyboardBoundsUserInfoKey等测试都不能获取正确的值。不知道为什么。。。
    
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"横屏%f",keyboardSize.height);
    float keyboardHeight = keyboardSize.height;
    
    // 获取键盘弹出的时间
    NSValue *animationDurationValue = [[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    //自定义的frame大小的改变的语句
    //...
    
    
    [UIView animateWithDuration:0.4 animations:^{
        
        _textView.frame = CGRectMake(0, SIZEHEIGHT - keyboardHeight - 130, SIZEWIDTH, 130);
    }];
    
}
-(void)KeyboardWillHide:(NSNotification *)notification{
    
    _textView.frame = CGRectMake(0, SIZEHEIGHT - 130, SIZEWIDTH, 130);
    
}
-(void)textViewDidChange:(UITextView *)textView{
    
    NSString *str = [textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    _numLabel.text = [NSString stringWithFormat:@"%ld",200-str.length];
    
    if (str.length > 200) {
        
        textView.text =  [str substringToIndex:200];
        
        _numLabel.text =@"0";
        
    }
}

- (void)openBtnClicked{

    _isOpen = !_isOpen;
    
    if (_isOpen == YES) {
        _circleView.colorState = ColorStateEmptyBlue;
    }else{
        _circleView.colorState = ColorStateEmptyGray;
    }
}

-(UIImage *)getImageFromView:(UIView *)theView
{
    //UIGraphicsBeginImageContext(theView.bounds.size);
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size, YES, theView.layer.contentsScale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
- (void)tapGestureClicked:(UITapGestureRecognizer *)tap{
    
    [_textView removeFromSuperview];
    [_backView removeFromSuperview];
    
    [_accountTextFeild resignFirstResponder];
    
}
#pragma mark- setupUI
-(void)setupUI{
    [self setupTable];
    [self setupBtn];
}
#pragma mark- 写笔记按钮
-(void)setupBtn{
    
    self.noteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:self.noteBtn];
    [self.noteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self).offset(-20);
        make.height.width.mas_equalTo(51);
    }];
    
    self.noteBtn.backgroundColor = Color_Main;
    [self.noteBtn setImage:[SCToolManager imageWithName:@"悬浮按钮icon" InBundle:@"note_image" className:[self class]] forState:UIControlStateNormal];
    [self.noteBtn addTarget:self action:@selector(clickNoteBtn) forControlEvents:UIControlEventTouchUpInside];
    self.noteBtn.layer.masksToBounds  = YES;
    self.noteBtn.layer.cornerRadius = 51/2;
    [self bringSubviewToFront:self.noteBtn];
}
-(void)clickNoteBtn{
    
    [[UIApplication sharedApplication].keyWindow addSubview:_backView];
    
    [[UIApplication sharedApplication].keyWindow addSubview:_textView];
    
    [_accountTextFeild becomeFirstResponder];
    
    /*移除跳转
    WriteNoteViewController *vc = [WriteNoteViewController new];
    vc.bijiInfo = [NSMutableDictionary dictionaryWithDictionary:self.classStateModel.currentInfo[@"info"]];
    vc.jmc = self.classStateModel.currentInfo[@"mlmc"];
    
    __weak typeof(self) weakSelf = self;
    
    self.presentToWriteNote = ^(SC_ChildViewController *control){
        
        weakSelf.presentToWriteNote(vc);
    };
    
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:YES completion:nil];
    */
}

#pragma mark- 设置table
-(void)setupTable{
    
    
    
     self.table = [[DXTableView alloc]initWithFrame:CGRectMake(0, 0, SIZEWIDTH, self.bounds.size.height) style:UITableViewStylePlain];
    [self addSubview:self.table];
    
    
    self.table.backgroundColor = Color_background;
    self.table.url = API_courseNote;
    self.table.cell = [NoteCell class];
    self.table.model = [NoteModel class];
    self.table.DXdelegate = self;
    self.table.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    __weak NoteView *weakSelf = self;

    self.table.cellLoadData= ^(UITableViewCell *cell,DXModel *model){
        NoteModel *mod = (NoteModel*)model;
        NoteCell *cel = (NoteCell*)cell;
        cel.model = mod;
        cel.selectionStyle = UITableViewCellSelectionStyleNone;
        [cel.zanBtn addTarget:weakSelf action:@selector(clickDianZanWith:) forControlEvents:UIControlEventTouchUpInside];
    };
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
     
}



#pragma mark- DXTableDelegate
-(void)DXTableShowBlankView:(BOOL)Bool withTabel:(UITableView *)table{
    
    if (self.classStateModel.ClassState == ClassStateNewJoin) {
        [self.blank removeFromSuperview];
        self.blank = nil;
    }
    if (!self.blank) {
         [_topBlank removeFromSuperview];
        self.blank = [[BlankView alloc]initWithFrame:CGRectMake(0, 0, self.table.frame.size.width, self.table.frame.size.height)];
        self.blank.icon.image = [SCToolManager imageWithName:@"空白页-笔记讨论" InBundle:@"note_image" className:[self class]];
        self.blank.label.font = NormalFont(30);
        if (self.classStateModel.ClassState == ClassStateKcls || self.classStateModel.ClassState == ClassStateNewJoin||self.classStateModel.ClassState == ClassStateSeleted) {
            self.blank.label.text = @"暂无笔记内容，快去发表吧！";
        }else{
            self.blank.label.text = @"暂无笔记!";
        }

        [self.blank adjustGapWithHeight:self.table.frame.size.height];
        
        [self.table addSubview:self.blank];
    }


    self.blank.hidden = !Bool;
    table.mj_footer.hidden = Bool;
}


#pragma mark- cell代理
-(void)clickDianZanWith:(UIButton*)sender{
    
    NoteCell *cell = (NoteCell*)[[sender superview]superview];
    
    NoteModel* model = cell.model;
    [MBProgressHUD showHUDAddedTo:[model getCurrentVC].view animated:YES];

    NSString* i;
    if (sender.selected) {
        i=@"0";
    }else{
        i=@"1";
    }
    NSMutableDictionary *para = [[NSMutableDictionary alloc]init];
    [para setObject:model.bjid forKey:@"bjid"];
    [para setObject:i forKey:@"dzzt"];
    [para setObject:self.classStateModel.kcid forKey:@"kcid"];

    SCHttpRequest *req = [[SCHttpRequest alloc]initWithApi:API_bijiDiznzan params:para];
    [[SCUDUtil sharedInstance] doPOSTConnect:req start:^(SCHttpRequest * _Nonnull req) {
        
    } success:^(SCHttpRequest * _Nonnull req, SCHttpResponse * _Nonnull resp) {
        if (resp.resultcode==0) {
            [MBProgressHUD hideAllHUDsForView:[model getCurrentVC].view animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[JLActionManager sharedInstance]showHUDWithLabelText:resp.resultMsg imageView:SucceedImage inView:[model getCurrentVC].view];
                if (sender.selected) {
                    model.isdz = @"0";
                    model.zanCount = [NSString stringWithFormat:@"%d", model.zanCount.intValue-1];
                    [self.table reloadData];
                    
                }else{
                    model.isdz = @"1";
                    model.zanCount = [NSString stringWithFormat:@"%d", model.zanCount.intValue+1];
                    [self.table reloadData];
                    
                }
            });
        }else{
            [[JLActionManager sharedInstance]showHUDWithLabelText:resp.resultMsg imageView:FailImage inView:[model getCurrentVC].view];
            [self.table reloadData];
        }
    } failure:^(SCHttpRequest * _Nonnull req, NSError * _Nonnull error) {
        
    } finish:^(SCHttpRequest * _Nonnull req, BOOL success) {
        
    }];
}

#pragma mark- 课程v逻辑处理
//未开放
-(void)unOpen{
    if (!_topBlank) {
        _topBlank = [[BlankView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    }
    _topBlank.icon.image = [SCToolManager imageWithName:@"空白页-笔记讨论" InBundle:@"note_image" className:[self class]];
    _topBlank.label.text = @"课程未开放，笔记已被封印~";
    _topBlank.label.font = NormalFont(30);
    [_topBlank adjustGapWithFrame:self.frame];

    [self addSubview:_topBlank];
    self.noteBtn.hidden = YES;
    
}
//加密
-(void)encrpyt{
    if (!_topBlank) {
        _topBlank = [[BlankView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    }
    _topBlank.icon.image = [SCToolManager imageWithName:@"空白页-笔记讨论" InBundle:@"note_image" className:[self class]];
    _topBlank.label.text = @"课程已加密，笔记待解密";
     _topBlank.label.font = NormalFont(30);
    [_topBlank adjustGapWithFrame:self.frame];

    [self addSubview:_topBlank];
    self.noteBtn.hidden = YES;
}

//未加入
-(void)unSelect{
    if (!_topBlank) {
        _topBlank= [[BlankView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
       
    }
     _topBlank.icon.image = [SCToolManager imageWithName:@"空白页-笔记讨论" InBundle:@"note_image" className:[self class]];
    if (self.classStateModel.ClassState == ClassStateisAuth) {
        _topBlank.label.text = @"课程已设置权限，笔记未开放!";
    }else{
        _topBlank.label.text = @"暂无笔记!";
    }
     _topBlank.label.font = NormalFont(30);
    [_topBlank adjustGapWithFrame:self.frame];
    [self addSubview:_topBlank];
    self.noteBtn.hidden = YES;
}
//kcls 已加入
-(void)normal{
    if (self.mlid==nil) {
        if (_tempMlid==nil) {
            [self noContent];
        }else{
            
            [self.blank adjustGapWithHeight:self.table.frame.size.height];
        }
    }else{
        [_topBlank removeFromSuperview];
        if(self.classStateModel.kcid!=nil){
            if (self.mlid!=nil) {
                if(![self.mlid isEqualToString:_tempMlid]){
                    self.tempMlid = self.mlid;
                    
                    self.table.request_Model.kcid = self.classStateModel.kcid;
                    self.table.request_Model.mlid = self.mlid;
                    
                    //self.mlid = nil;//赋值为nil,防止多次请求造成崩溃
                }else{
                    
                    self.table.request_Model.kcid = self.classStateModel.kcid;
                    self.table.request_Model.mlid = self.mlid;
                    
                    //self.mlid = nil;//赋值为nil,防止多次请求造成崩溃
                }
                
                self.noteBtn.hidden = NO;
                [self bringSubviewToFront:self.noteBtn];
            }
        }
    }
}

//新加入
-(void)newJoin{

    [self normal];
    
}
//加入后无可播素材
-(void)noContent{
    [_topBlank removeFromSuperview];
    _topBlank=nil;
    [self layoutIfNeeded];
    _topBlank= [[BlankView alloc]initWithFrame:CGRectMake(0, 0,self.frame.size.width, self.frame.size.height)];
    _topBlank.icon.image = [SCToolManager imageWithName:@"空白页-笔记讨论" InBundle:@"note_image" className:[self class]];
    _topBlank.label.text = @"暂无笔记";
    _topBlank.label.font = NormalFont(30);
    [_topBlank adjustGapWithHeight:self.frame.size.height];
    [self addSubview:_topBlank];
    self.noteBtn.hidden = YES;

}

#pragma mark- 懒加载

@end
